<template>
  <div class="carousel-banner">
    <!-- 轮播图内容 -->
    <div v-if="banners.length > 0" class="carousel-content">
      <swiper
      :modules="modules"
      :slides-per-view="1"
      :space-between="0"
      :loop="banners.length > 1"
      :autoplay="banners.length > 1 ? {
        delay: 4000,
        disableOnInteraction: false,
        pauseOnMouseEnter: true,
      } : false"
      :pagination="{
        clickable: true,
        dynamicBullets: false,
        enabled: banners.length > 1
      }"
      :navigation="{ enabled: banners.length > 1 }"
      :effect="'slide'"
      :speed="800"
      :allow-touch-move="true"
      :simulate-touch="true"
      class="carousel-swiper"
      @swiper="onSwiper"
      @slide-change="onSlideChange"
    >
      <swiper-slide v-for="banner in banners" :key="banner.id">
        <div 
          class="banner-slide"
          @click="handleBannerClick(banner)"
        >
          <img 
            :src="getFullImageUrl(banner.imageUrl)"
            :alt="banner.title"
            class="banner-image"
            @error="(e) => handleImageError(e, 'banner')"
            @load="onImageLoad"
            loading="eager"
            crossorigin="anonymous"
          />
          <div class="banner-overlay">
            <div class="banner-content">
              <h2 class="banner-title">{{ banner.title }}</h2>
              <p v-if="banner.description" class="banner-description">
                {{ banner.description }}
              </p>
              <div v-if="banner.linkUrl || (banner.targetType && banner.targetId)" class="banner-action">
                <el-button type="primary" size="large" round @click.stop="handleBannerClick(banner)">
                  了解更多
                  <el-icon><ArrowRight /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </swiper-slide>
    </swiper>
    </div>
    
    <!-- 无数据时的占位内容 -->
    <div v-else-if="!loading" class="carousel-placeholder">
      <div class="placeholder-content">
        <el-icon class="placeholder-icon"><Picture /></el-icon>
        <h3>暂无轮播图</h3>
        <p>管理员还未添加轮播图内容</p>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-else class="carousel-loading">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowRight, Picture, Loading } from '@element-plus/icons-vue'
import { Swiper, SwiperSlide } from 'swiper/vue'
import { Navigation, Pagination, Autoplay, EffectFade } from 'swiper/modules'

// Import Swiper core and required modules
import 'swiper/css'
import 'swiper/css/navigation'
import 'swiper/css/pagination'
import 'swiper/css/effect-fade'
import { bannerApi, type CarouselBanner } from '@/api/banner'
import { getFullImageUrl, handleImageError, preloadImages } from '@/utils/imageUtils'

const router = useRouter()
const modules = [Navigation, Pagination, Autoplay]

// 响应式数据
const banners = ref<CarouselBanner[]>([])
const loading = ref(true)

// Swiper 实例
const swiperInstance = ref<any>(null)

const onSwiper = (swiper: any) => {
  console.log('Swiper initialized:', swiper)
  swiperInstance.value = swiper
  
  // 确保自动播放启动
  if (banners.value.length > 1 && swiper.autoplay) {
    swiper.autoplay.start()
    console.log('Autoplay started')
  }
}

const onSlideChange = (swiper: any) => {
  console.log('Slide changed to:', swiper.activeIndex)
}

// 获取轮播图数据
const fetchCarouselBanners = async () => {
  try {
    loading.value = true
    console.log('🎠 CarouselBanner: 开始获取轮播图数据...')
    
    const response = await bannerApi.getCarouselList()
    console.log('🎠 CarouselBanner: 轮播图API响应:', response)
    
    if (!response || !response.data) {
      throw new Error('API响应数据格式错误')
    }
    
    // 获取所有轮播图数据
    const allBanners = Array.isArray(response.data) ? response.data : []
    
    // 过滤有效的轮播图 (status = 1 表示启用)
    const validBanners = allBanners.filter((banner: CarouselBanner) => {
      const isValid = banner && 
             banner.status === 1 && 
             banner.title && 
             banner.imageUrl
      
      console.log(`🎠 轮播图 ${banner?.id} 验证:`, {
        有标题: !!banner?.title,
        有图片: !!banner?.imageUrl,
        状态启用: banner?.status === 1,
        整体有效: isValid
      })
      
      return isValid
    })
    
    // 按排序字段排序
    validBanners.sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))
    
    console.log(`🎠 CarouselBanner: 获取到轮播图 ${allBanners.length} 个，有效的 ${validBanners.length} 个`)
    console.log('🎠 CarouselBanner: 有效轮播图列表:', validBanners.map(b => ({
      id: b.id,
      title: b.title,
      imageUrl: b.imageUrl,
      sortOrder: b.sortOrder,
      linkType: b.linkType
    })))
    
    banners.value = validBanners
    
    // 数据加载完成后，更新Swiper实例
    if (swiperInstance.value) {
      setTimeout(() => {
        console.log('🎠 CarouselBanner: 更新Swiper实例')
        swiperInstance.value.update()
        
        // 如果有多个轮播图，启动自动播放
        if (validBanners.length > 1 && swiperInstance.value.autoplay) {
          swiperInstance.value.autoplay.start()
          console.log('🎠 CarouselBanner: 自动播放已启动')
        }
      }, 200)
    }
    
    // 预加载图片以提升用户体验
    if (validBanners.length > 0) {
      const imageUrls = validBanners
        .map(banner => getFullImageUrl(banner.imageUrl))
        .filter(Boolean)
        
      console.log('🎠 CarouselBanner: 开始预加载图片:', imageUrls)
      
      preloadImages(imageUrls).then(results => {
        const successCount = results.filter(success => success).length
        const failedCount = results.length - successCount
        
        console.log(`🎠 CarouselBanner: 图片预加载完成 - 成功: ${successCount}, 失败: ${failedCount}`)
        
        if (failedCount > 0) {
          console.warn(`🎠 CarouselBanner: ${failedCount} 张轮播图图片加载失败`)
        }
      }).catch(error => {
        console.error('🎠 CarouselBanner: 图片预加载出错:', error)
      })
    }
    
    // 如果没有有效数据，显示提示
    if (validBanners.length === 0) {
      console.warn('🎠 CarouselBanner: 没有找到有效的轮播图数据')
      ElMessage.warning('暂无轮播图内容')
    }
    
  } catch (error: any) {
    console.error('🎠 CarouselBanner: 获取轮播图失败:', error)
    
    // 根据错误类型显示不同提示
    let errorMessage = '获取轮播图数据失败'
    if (error.message?.includes('timeout')) {
      errorMessage = '请求超时，请检查网络连接'
    } else if (error.message?.includes('Network Error')) {
      errorMessage = '网络连接失败，请稍后重试'
    } else if (error.response?.status === 404) {
      errorMessage = '轮播图接口不存在'
    } else if (error.response?.status >= 500) {
      errorMessage = '服务器内部错误，请稍后重试'
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}

// 处理轮播图点击
const handleBannerClick = (banner: CarouselBanner) => {
  console.log('🎠 CarouselBanner: 轮播图被点击:', {
    id: banner.id,
    title: banner.title,
    linkType: banner.linkType,
    targetType: banner.targetType,
    targetId: banner.targetId,
    linkUrl: banner.linkUrl
  })
  
  // linkType: 1-无链接, 2-内部链接, 3-外部链接
  if (banner.linkType === 1) {
    console.log('🎠 CarouselBanner: 轮播图无链接配置')
    return
  }
  
  if (banner.linkType === 2 && banner.targetType && banner.targetId) {
    // 内部链接 - 跳转到应用内页面
    const routes: Record<string, string> = {
      culture: `/culture/${banner.targetId}`,
      tutorial: `/tutorial/${banner.targetId}`,
      news: `/news/${banner.targetId}`
    }
    
    const targetRoute = routes[banner.targetType]
    if (targetRoute) {
      console.log(`🎠 CarouselBanner: 跳转到内部页面: ${targetRoute}`)
      router.push(targetRoute)
    } else {
      console.warn(`🎠 CarouselBanner: 未知的目标类型: ${banner.targetType}`)
      ElMessage.warning('页面链接配置错误')
    }
  } else if (banner.linkType === 3 && banner.linkUrl) {
    // 外部链接 - 在新窗口打开
    console.log(`🎠 CarouselBanner: 打开外部链接: ${banner.linkUrl}`)
    try {
      window.open(banner.linkUrl, '_blank', 'noopener,noreferrer')
    } catch (error) {
      console.error('🎠 CarouselBanner: 打开外部链接失败:', error)
      ElMessage.error('无法打开链接')
    }
  } else {
    console.warn('🎠 CarouselBanner: 轮播图链接配置不完整:', {
      linkType: banner.linkType,
      targetType: banner.targetType,
      targetId: banner.targetId,
      linkUrl: banner.linkUrl
    })
    ElMessage.warning('链接配置不完整')
  }
}

// 图片加载完成处理
const onImageLoad = (event: Event) => {
  const img = event.target as HTMLImageElement
  console.log('🖼️ CarouselBanner: 图片加载完成:', {
    src: img.src,
    naturalWidth: img.naturalWidth,
    naturalHeight: img.naturalHeight,
    complete: img.complete
  })
  
  // 确保图片显示
  img.style.opacity = '1'
  img.style.visibility = 'visible'
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCarouselBanners()
})

// 暴露给父组件的方法
defineExpose({
  refresh: fetchCarouselBanners
})
</script>

<style scoped>
.carousel-banner {
  width: 100%;
  height: 0;
  padding-bottom: 37.5%; /* 16:6 比例 = 37.5% */
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
  margin: 0 auto;
  background: #f5f7fa;
}

/* 确保内容绝对定位填充容器 */
.carousel-banner > * {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.carousel-swiper {
  width: 100%;
  height: 100%;
}

.banner-slide {
  width: 100%;
  height: 100%;
  position: relative;
  cursor: pointer;
  transition: transform 0.3s ease;
  overflow: hidden;
}

.banner-image {
  width: 100%;
  height: 100%;
  /* 使用 cover 填充容器，确保没有留白 */
  object-fit: cover;
  object-position: center;
  transition: transform 0.3s ease;
  /* 确保图片立即显示，避免透明度问题 */
  opacity: 1 !important;
  display: block;
  /* 确保图片在加载时就显示 */
  visibility: visible;
}

@keyframes fadeInImage {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.banner-slide:hover {
  transform: scale(1.02);
}

.banner-slide:hover .banner-image {
  transform: scale(1.05);
}

.banner-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  /* 减轻遮罩效果，让图片更清晰 */
  background: linear-gradient(
    180deg,
    rgba(0, 0, 0, 0.15) 0%,
    rgba(0, 0, 0, 0.05) 40%,
    rgba(0, 0, 0, 0.05) 60%,
    rgba(0, 0, 0, 0.25) 100%
  );
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30px 20px;
  pointer-events: none; /* 让遮罩层不阻止点击事件 */
}

/* 让按钮可以点击 */
.banner-overlay .banner-action {
  pointer-events: auto;
}

.banner-content {
  text-align: center;
  color: #fff;
  max-width: 700px;
  animation: fadeInUp 0.8s ease-out;
}

.banner-title {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 10px;
  text-shadow: 1px 1px 8px rgba(0, 0, 0, 0.7);
  line-height: 1.4;
  letter-spacing: 0.3px;
}

.banner-description {
  font-size: 14px;
  margin-bottom: 18px;
  text-shadow: 1px 1px 4px rgba(0, 0, 0, 0.6);
  line-height: 1.5;
  opacity: 0.9;
  max-width: 500px;
  margin-left: auto;
  margin-right: auto;
}

.banner-action {
  margin-top: 20px;
}

.banner-action .el-button {
  font-size: 14px;
  padding: 8px 24px;
  background: linear-gradient(135deg, #d32f2f, #f57c00);
  border: none;
  border-radius: 20px;
  box-shadow: 0 3px 12px rgba(211, 47, 47, 0.2);
  transition: all 0.3s ease;
  font-weight: 500;
  letter-spacing: 0.2px;
}

.banner-action .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(211, 47, 47, 0.4);
}

/* Swiper 自定义样式 */
:deep(.swiper-pagination) {
  bottom: 20px;
}

:deep(.swiper-pagination-bullet) {
  width: 12px;
  height: 12px;
  background: rgba(255, 255, 255, 0.5);
  opacity: 1;
  transition: all 0.3s ease;
}

:deep(.swiper-pagination-bullet-active) {
  background: #fff;
  transform: scale(1.2);
}

:deep(.swiper-button-next),
:deep(.swiper-button-prev) {
  color: #fff;
  background: rgba(0, 0, 0, 0.3);
  width: 50px;
  height: 50px;
  border-radius: 50%;
  transition: all 0.3s ease;
}

:deep(.swiper-button-next:hover),
:deep(.swiper-button-prev:hover) {
  background: rgba(0, 0, 0, 0.5);
  transform: scale(1.1);
}

:deep(.swiper-button-next::after),
:deep(.swiper-button-prev::after) {
  font-size: 20px;
  font-weight: bold;
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .carousel-banner {
    padding-bottom: 40%; /* 调整为 5:2 比例 */
  }
  
  .banner-title {
    font-size: 24px;
  }
  
  .banner-description {
    font-size: 13px;
  }
}

@media (max-width: 768px) {
  .carousel-banner {
    padding-bottom: 50%; /* 调整为 2:1 比例 */
    border-radius: 10px;
  }
  
  .banner-title {
    font-size: 20px;
    margin-bottom: 8px;
  }
  
  .banner-description {
    font-size: 12px;
    margin-bottom: 16px;
  }
  
  .banner-action .el-button {
    font-size: 13px;
    padding: 6px 18px;
  }
  
  .banner-overlay {
    padding: 20px 16px;
  }
  
  :deep(.swiper-button-next),
  :deep(.swiper-button-prev) {
    width: 40px;
    height: 40px;
  }

  :deep(.swiper-button-next::after),
  :deep(.swiper-button-prev::after) {
    font-size: 16px;
  }
}

@media (max-width: 480px) {
  .carousel-banner {
    padding-bottom: 60%; /* 调整为 5:3 比例 */
    border-radius: 8px;
  }
  
  .banner-title {
    font-size: 18px;
    margin-bottom: 6px;
  }
  
  .banner-description {
    font-size: 11px;
    margin-bottom: 12px;
  }
  
  .banner-overlay {
    padding: 15px 12px;
  }
  
  .banner-action .el-button {
    font-size: 12px;
    padding: 5px 15px;
  }
  
  :deep(.swiper-button-next),
  :deep(.swiper-button-prev) {
    width: 35px;
    height: 35px;
  }

  :deep(.swiper-button-next::after),
  :deep(.swiper-button-prev::after) {
    font-size: 14px;
  }
}

/* 占位内容样式 */
.carousel-placeholder,
.carousel-loading {
  width: 100%;
  height: 0;
  padding-bottom: 37.5%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  color: #666;
}

.carousel-placeholder > *,
.carousel-loading > * {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.placeholder-content,
.carousel-loading {
  text-align: center;
}

.placeholder-icon,
.loading-icon {
  font-size: 48px;
  color: #ccc;
  margin-bottom: 16px;
}

.loading-icon {
  animation: rotate 2s linear infinite;
}

.carousel-placeholder h3,
.carousel-loading p {
  margin: 8px 0;
  color: #666;
}

.carousel-placeholder p {
  color: #999;
  font-size: 14px;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
